package com.example.springcloud.account.controller;

import com.example.springcloud.account.service.AccountService;
import com.example.springcloud.account.service.tcc.AccountTCCService;
import com.example.springcloud.account.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;

@Slf4j
@RestController
@RequestMapping("/account")
public class AccountController {

    @Autowired
    private AccountService accountService;

    @Autowired
    private AccountTCCService accountTCCService;

    @PostMapping("/deduct")
    public Result<Void> deduct(@RequestParam("userId") Long userId,
                               @RequestParam("money") BigDecimal money) {
        log.info("收到扣减余额请求 - AT 模式: userId={}, money={}", userId, money);
        // ✅ 分布式事务：不要捕获异常，让异常向上抛出触发全局回滚
        accountService.deduct(userId, money);
        return Result.success();
    }

    @PostMapping("/deduct/tcc/try")
    public Result<Void> deductTccTry(@RequestParam("userId") Long userId,
                                     @RequestParam("money") BigDecimal money) {
        log.info("收到扣减余额请求 - TCC Try: userId={}, money={}", userId, money);
        try {
            accountTCCService.tryDeduct(userId, money);
            return Result.success();
        } catch (Exception e) {
            log.error("TCC Try 扣减余额失败", e);
            return Result.error(e.getMessage());
        }
    }

    @PostMapping("/deduct/xa")
    public Result<Void> deductXa(@RequestParam("userId") Long userId,
                                 @RequestParam("money") BigDecimal money) {
        log.info("收到扣减余额请求 - XA 模式: userId={}, money={}", userId, money);
        // ✅ 分布式事务：不要捕获异常，让异常向上抛出触发全局回滚
        accountService.deductXa(userId, money);
        return Result.success();
    }

    @GetMapping("/health")
    public Result<String> health() {
        return Result.success("Account Service is running");
    }
}
